package analyze;

import java.awt.Color;
import java.util.ArrayList;

import logging.Logger;

import object.Connection;
import object.Node;
import util.ColorUtil;

public class AnalyzeDisjointness extends AnalyzeBase {
	
	@Override
	public ArrayList<AnalyzeInfo> Analyze(ArrayList<Node> nodes) {
		
		Logger.getInstance().log(Logger.TRACE, "Starting Disjoint Analysis");
		
		ArrayList<AnalyzeInfo> messages = new ArrayList<AnalyzeInfo>();
		
		if( nodes.isEmpty() )
		{
			Logger.getInstance().log(Logger.TRACE, "Disjoint Analysis: Ended due to lack of nodes");
			messages.add(new AnalyzeInfo(0, "No nodes to analyze", 0));
			return messages;
		}
		
		ArrayList<Node> Visited = new ArrayList<Node>();	//holds the global list of visited nodes
		ArrayList<Node> Current = new ArrayList<Node>();	//holds the list of visited nodes for current network
		
		Node c;
		Color hold;
		int numCurrent;		//Counts the number of nodes in the current list
		int numFollowed;	//counts the number of nodes we have pulled connection information from
		int numNetworks=0;	//Counts the number of separate networks
		int numSingles=0;	//Counts the number of nodes not belonging to a network
		
		
		for( Node d: nodes)
		{
			//If the node has already been included in a network, skip it and go to the next node
			if( Visited.contains(d) )
				continue; 
			
			
			Current.add(d);		//add the node to the Current Network
			numCurrent = 1;		
			numFollowed = 0;
			numNetworks++;
			hold = ColorUtil.newColor();	//get a new color for the network
		
			while( numCurrent != numFollowed )	//while we havn't visited every node in the network
			{
				c = Current.get(numFollowed);	//move to the next node in out current network
				c.color = hold;
				if( c.getConnections().isEmpty())	//if that node has no connections its a stand-alone node
				{
					c.color = Color.red;
					numNetworks--;
					numSingles++;
				}
				else	//Check to see if node connects to a new node
					for( Connection path : c.getConnections() )
					{
						path.color = hold;
						if( Current.contains( path.getN1() ) == false )
						{
							Current.add(path.getN1());
							numCurrent++;
						}
						else if ( Current.contains( path.getN2()) == false )
						{
							Current.add(path.getN2());	
							numCurrent++;
						}
					}
				numFollowed++;
			}
		Visited.addAll(Current);
		Current.clear();
		
		}
		
		
		messages.add(new AnalyzeInfo(1,"Number of Networks", numNetworks));
		messages.add(new AnalyzeInfo(1,"Number of single nodes", numSingles));
		
		
		Logger.getInstance().log(Logger.TRACE, "Done with Disjoint Analysis");
		return messages;
	}

}